<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

class CouponCodeUnavailableException extends Exception
{
    public function __construct($message, int $code = 403)
    {
        parent::__construct($message, $code);
    }

    /**
     * 当这个异常被处罚时，则会调用 render 方法来输出给用户
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function render(Request $request)
    {
        // 如果用户是通过 api请求 则返回 json 格式错误
        if ($request->ajax()) {
            return response()->json(['msg' => $this->message], $this->code);
        }

        // 否则返回上一页
        return redirect()->back()->withErrors(['coupon_code' => $this->message]);
    }
}
